﻿using System;
using System.Drawing;
using ProjectAutumn.Graphics;
using SlimDX.Direct2D;
using SlimDX.DXGI;
using Bitmap = SlimDX.Direct2D.Bitmap;
using Color = ProjectAutumn.Graphics.Color;

namespace ProjectAutumn.GraphicsDevice.Direct2D
{
    sealed class Direct2DTexture : Texture
    {
        internal Bitmap Internal;
        public Direct2DTexture(string file, RenderTarget target)
        {
            //TODO: Get a better way of doing this
            Image tmp = Image.FromFile(file);
            System.Drawing.Bitmap image = new System.Drawing.Bitmap(tmp);
            Internal = new Bitmap(target, new Size(image.Width, image.Height), new BitmapProperties
            {
                PixelFormat = new PixelFormat
                {
                    AlphaMode = AlphaMode.Premultiplied,
                    Format = Format.B8G8R8A8_UNorm
                }
            });
            Color[] color = new Color[Width * Height];
            for (int y = 0; y < Height; y++)
                for (int x = 0; x < Width; x++)
                    color[x + y * Width] = new Color((uint)image.GetPixel(x, y).ToArgb());
            SetData(color);
            tmp.Dispose();
            image.Dispose();
        }
        public Direct2DTexture(int width, int height, RenderTarget target)
        {
            Internal = new Bitmap(target, new Size(width, height), new BitmapProperties
            {
                    PixelFormat = new PixelFormat
                    {
                            AlphaMode = AlphaMode.Premultiplied,
                            Format = Format.B8G8R8A8_UNorm
                    }
            });
        }
        public override void SetData(Color[] color, int start, int length)
        {
            if (start != 0 && color.Length != length) throw new Exception();
            byte[] buffer = new byte[color.Length * 4];
            for (int i = 0; i < color.Length; i++)
            {
                buffer[i * 4 + 3] = color[i].A;
                buffer[i * 4 + 2] = color[i].R;
                buffer[i * 4 + 1] = color[i].G;
                buffer[i * 4] = color[i].B;
            }
            Internal.FromMemory(buffer, 0);
        }
        public override int Width
        {
            get { return (int)Internal.Size.Width; }
        }
        public override int Height
        {
            get { return (int)Internal.Size.Height; }
        }
        public override void Dispose()
        {
            Internal.Dispose();
        }
    }
}
